package com.balance.anole.client.common.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;

import com.balance.anole.business.to.BusinessDateTO;
import com.balance.anole.client.common.dao.BusinessDateDAO;

public class BusinessDateDAOImpl extends BaseDAOImpl implements BusinessDateDAO {

	@SuppressWarnings("unchecked")
	@Override
	public BusinessDateTO getCurrentBusinessDate() {
		Date currentBusinessDate = null;
		String hql = "select max(b.businessDate) from " + BusinessDateTO.class.getName() + " b";
		List<Date> dates = getSession().createQuery(hql).list();
		if(dates != null && dates.size() > 0){
			currentBusinessDate = dates.get(0);
			hql = "from " + BusinessDateTO.class.getName() + " b where b.businessDate = :businessDate";
			List<BusinessDateTO> results = getSession().createQuery(hql).setDate("businessDate", currentBusinessDate).list();
			if(results != null && results.size() > 0){
				return results.get(0);
			}

		}

		return null;
	}

	@Override
	public void insertOrUpdateBusinessDate(BusinessDateTO businessDate) {
		getHibernateTemplate().saveOrUpdate(businessDate);
	}

	@SuppressWarnings("unchecked")
	@Override
	public BusinessDateTO getBusinessDateByCurrentBusinessDate(
			Date currentBusinessDate) {
		String hql = "from " + BusinessDateTO.class.getName() + " b where b.businessDate = :businessDate";
		Query query = getSession().createQuery(hql).setParameter("businessDate", currentBusinessDate);
		List<BusinessDateTO> results = query.list();
		if(results != null && results.size() == 1){
			return results.get(0);
		}
		return null;
	}
}
